package com.labot.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.labot.dao.ConfigDao;
import com.labot.model.Config;
import com.labot.types.ConstantsGrupsType;
import com.labot.types.ConstantsType;

/**
 * This class interacts with Hibernate session to save/delete and
 * retrieve Config objects.
 *
 * @author Ing. Enrique Barbeito
*/
@Repository("configDao")
public class ConfigDaoHibernate extends GenericDaoHibernate<Config, Long> implements ConfigDao {

    /**
     * Constructor that sets the entity to User.class.
     */
    public ConfigDaoHibernate() {
        super(Config.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<Config> getConfigs(ConstantsGrupsType type) {
        Query qry = getSession().createQuery("from Config c where c.configGroup = '" + type.toString() + "' order by upper(c.constant)");
        return qry.list();
    }
    
    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<Config> getAllConfigs() {
        Query qry = getSession().createQuery("from Config c order by upper(c.constant)");
        return qry.list();
    }

    /**
     * {@inheritDoc}
     */
    public Config saveConfig(Config config) {
        if (log.isDebugEnabled()) {
            log.debug("config's id: " + config.getId());
        }
        getSession().saveOrUpdate(config);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getSession().flush();
        return config;
    }

    /**
     * Overridden simply to call the saveUser method. This is happening
     * because saveUser flushes the session and saveObject of BaseDaoHibernate
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public Config save(Config config) {
        return this.saveConfig(config);
    }


    /**
     * {@inheritDoc}
    */
    @SuppressWarnings(value = "unchecked")
    public Config getConfig(ConstantsType constant) {    
    	List<Config> configs = getSession().createCriteria(Config.class).add(Restrictions.eq("constant", constant)).list();
        if (configs.isEmpty()) {
            return null;
        } else {
            return (Config) configs.get(0);
        }
    }

	@Override
	public void excuteBatch(String hql) {
		Query qry = getSession().createQuery(hql);
		qry.executeUpdate();		
	}

}
